package com.llongwill.slg.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static com.llongwill.slg.gateway.common.GatewayConstants.KEYS_SCHOOL_ID;
import static com.llongwill.slg.gateway.common.GatewayConstants.SGL_USERID;
import static com.xiangff.base.framework.constants.SecurityConstants.*;

/**
 * 全局过滤器，为请求添加 Same-Token
 */
@Component
public class ForwardAuthFilter implements GlobalFilter {

    private static final Long RENEWTOKENTIME = 864000L;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> schoolIds = exchange.getRequest().getHeaders().get(SCHOOL_ID_HEADER);
        String userName = StpUtil.isLogin() ? String.valueOf(StpUtil.getSession().get(USER_HEADER)) : "";
        try {
            userName = URLEncoder.encode(userName, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
        }

        // 获取过期时间
//        long tokenTimeoutTime = StpUtil.getTokenTimeout();
//        boolean tokenTimeout = tokenTimeoutTime - RENEWTOKENTIME <= 0;
//        //token没过期，每次请求都刷新过期时间
//        if (tokenTimeout) {
//            // 用于token续期
//            StpUtil.renewTimeout(RENEWTOKENTIME);
//            StpUtil.updateLastActivityToNow();
//        }
        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                // 为请求追加 Same-Token 参数
                .header(SGL_USERID, StpUtil.isLogin() ? String.valueOf(StpUtil.getLoginId()) : "")
                .header(USER_ID_HEADER, StpUtil.isLogin() ? String.valueOf(StpUtil.getLoginId()) : "")
                .header(USER_HEADER, StpUtil.isLogin() ? userName : "")
                .header(SCHOOL_ID_HEADER, StpUtil.isLogin() ? CollectionUtils.isNotEmpty(schoolIds) ? schoolIds.get(0) : String.valueOf(StpUtil.getSession().get(KEYS_SCHOOL_ID)) : "")
                .header(ROLE_HEADER, StpUtil.isLogin() ? CollectionUtils.isNotEmpty(StpUtil.getRoleList()) ? String.join(",", StpUtil.getRoleList()) : "" : "")
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    }
}
